﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SqliteORM;

namespace ChgDoc.Entity
{
    [Table]
    public class PageHitCount : TableBase<PageHitCount>
    {
        [PrimaryKey(true)]
        public long Id { get; set; }

        [Field(IsCaseInsensitive = true)]
        public string RequestUrl { get; set; }

        [ForeignKey( typeof( PageResponse ) )]
        public long PageResponseId { get; set; }

        public string PageResponse { get; set; }

        [Field]
        public long HitCount { get; set; }

        
        internal static void Track(string url, PageResponse pageResp)
        {
            var hitCount = Get(ad => ad.Select().Where(Where.And(Where.Equal("RequestUrl", url), Where.Equal("PageResponseId", pageResp.Id))).FirstOrDefault());
            if ( hitCount == null)
                hitCount = new PageHitCount() { RequestUrl = url, PageResponseId = pageResp.Id } ;

            hitCount.HitCount++;
            hitCount.Save();
        }

        internal static List<PageHitCount> ReadAll()
        {
            using (var adapt = TableAdapter<Mash<PageHitCount, PageResponse>>.Open())
            {
                return (from ad in adapt.Select().OrderBy(t => t.Table1.HitCount, true)
                        select new PageHitCount()
                            {
                                  Id = ad.Table1.Id,
                                  PageResponse = ad.Table2.Url,
                                  RequestUrl = ad.Table1.RequestUrl,
                                  HitCount = ad.Table1.HitCount
                            }).ToList();
            }
        }
    }
}